﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Threading.Tasks;
using SeachAndShareDemo.Models;
using Windows.Storage.Streams;

namespace SeachAndShareDemo.ViewModels
{
    public class SearchResultsViewModel
    {
        ObservableCollection<ColorItem> _Colors = new ObservableCollection<ColorItem>();
        public ObservableCollection<ColorItem> Colors { get { return _Colors; } }

        public void Search(string query)
        {
            var colors = typeof(Windows.UI.Colors)
                .GetRuntimeProperties().Select(x => new ColorItem
                {
                    Color = (Windows.UI.Color)x.GetValue(null),
                    Name = x.Name,
                    Thumb = new Uri(string.Format("ms-appx:///Thumbs/{0}.png",
                        ((Windows.UI.Color)x.GetValue(null)).ToString().TrimStart('#'))),
                });
            var matches = colors.Where(x => x.Name.ToLower().Contains(query.ToLower()));
            foreach (var item in matches)
                this.Colors.Add(item);
        }

        public void SuggestionsRequested(Windows.UI.Xaml.Controls.SearchBox s, Windows.UI.Xaml.Controls.SearchBoxSuggestionsRequestedEventArgs e)
        {
            var rsuggestions = Colors
                .Where(x => x.Name.StartsWith(e.QueryText, StringComparison.CurrentCultureIgnoreCase))
                .Take(2);

            var qsuggestions = Colors
                .Where(x => !rsuggestions.Contains(x))
                .Where(x => x.Name.ToLower().Contains(e.QueryText.ToLower()))
                .Select(x => x.Name)
                .Take(4 - rsuggestions.Count());

            // query suggestions
            e.Request.SearchSuggestionCollection.AppendQuerySuggestions(qsuggestions);

            if (qsuggestions.Any() && rsuggestions.Any())
                e.Request.SearchSuggestionCollection.AppendSearchSeparator("Exact match");

            // result suggestions
            foreach (var item in rsuggestions)
            {
                var thumb = RandomAccessStreamReference.CreateFromUri(item.Thumb);
                e.Request.SearchSuggestionCollection.AppendResultSuggestion
                    (item.Name, item.Color.ToString(), item.Name, thumb, string.Empty);
            }
        }
    }
}
